<!--
 * @Author: your name
 * @Date: 2020-12-27 12:48:22
 * @LastEditTime: 2021-03-28 13:38:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \white-jotter-blog-vue\src\views\admin\admin-book\index.vue
-->
<template>
  <div>
    <admin-breadcrumb :breadcrumb="breadcrumb" />
    <!-- <edit-form @onSubmit="getBookList()" ref="edit"></edit-form> -->
    <el-card>
      <!-- 图书搜索，添加 -->
      <el-row :gutter="0">
        <!-- 图书搜索 -->
        <el-col :span="8">
          <el-input placeholder="搜索图书" v-model="queryInfo.query" clearable @clear="getBookList">
            <el-button slot="append" icon="el-icon-search" @click="getBookList"></el-button>
          </el-input>
        </el-col>
        <!-- 图书添加 -->
        <el-col :span="2">
          <el-button type="primary" @click="addAndEditDialogVisible = true; dialogTitle='添加图书'">添加图书</el-button>
        </el-col>
      </el-row>
      <!-- 图书表格 -->
      <el-table id="bookTable" :data="bookList" stripe style="width: 100%">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-form label-position="left" inline>
              <el-form-item>
                <span>{{ scope.row.abs }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="书名（展开查看摘要）" fit />
        <el-table-column prop="category.name" label="分类" width="100" />
        <el-table-column prop="author" label="作者" fit />
        <el-table-column prop="date" label="出版日期" width="120" />
        <el-table-column prop="press" label="出版社" fit />
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <!-- 修改图书信息 -->
            <el-tooltip effect="dark" content="修改图书信息" placement="top" :open-delay="500" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row)" />
              @click="addAndEditDialogVisible = true; dialogTitle='添加图书'"
            </el-tooltip>
            <!-- 删除图书 -->
            <el-tooltip effect="dark" content="删除图书" placement="top" :open-delay="500" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteBook(scope.row.id)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <div class="page">
      <el-pagination @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" background layout="total, prev, pager, next, jumper" :total="count"></el-pagination>
    </div>
    <!-- 添加/修改图书的对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="addAndEditDialogVisible" width="50%" :close-on-click-modal="false" @close="addAndEditDialogClosed">
      <el-form :model="addAndEditForm" style="text-align: left" ref="addFormRef" :rules=bookRules label-width="70px">
        <el-form-item label="书名" prop="title">
          <el-input v-model="addAndEditForm.title" autocomplete="off" placeholder="不加《》"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="addAndEditForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="press">
          <el-input v-model="addAndEditForm.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="date">
          <el-input v-model="addAndEditForm.date" autocomplete="off" placeholder="2020-12-01的形式"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-input v-model="addAndEditForm.cover" autocomplete="off" placeholder="图片 URL" disabled></el-input>
          <img-upload @onUpload="uploadImg" ref="imgUploadRef"></img-upload>
        </el-form-item>
        <el-form-item label="简介" prop="abs">
          <el-input type="textarea" v-model="addAndEditForm.abs" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="cid">
          <el-select v-model="addAndEditForm.cid" placeholder="请选择分类">
            <el-option label="文学" value="1"></el-option>
            <el-option label="流行" value="2"></el-option>
            <el-option label="文化" value="3"></el-option>
            <el-option label="生活" value="4"></el-option>
            <el-option label="经管" value="5"></el-option>
            <el-option label="科技" value="6"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAndEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImgUpload from "components/content/ImgUpload";
export default {
  name: "BookManagement",
  metaInfo: {
    title: "后台管理-图书管理",
  },
  data() {
    return {
      // 面包屑导航
      breadcrumb: ["内容管理", "图书列表"],

      // 查询文章的对象
      queryInfo: {
        // 查询的参数，可为空
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页的条目数
        pageSize: 10,
      },

      // 查询出来的图书列表
      bookList: [],
      // 查询出来的图书总数
      count: 0,

      // 添加修改图书对话框的标题
      dialogTitle: "",
      // 显示添加图书的表单
      addAndEditDialogVisible: false,
      bookRules: {
        title: [{ required: true, message: "title不能为空", trigger: "blur" }],
        author: [
          { required: true, message: "author不能为空", trigger: "blur" },
        ],
        press: [{ required: true, message: "press不能为空", trigger: "blur" }],
        date: [{ required: true, message: "date不能为空", trigger: "blur" }],
        cover: [{ required: true, message: "cover不能为空", trigger: "blur" }],
        abs: [{ required: true, message: "abs不能为空", trigger: "blur" }],
        cid: [{ required: true, message: "cid不能为空", trigger: "blur" }],
      },

      // 添加图书的对话框
      addAndEditForm: {
        title: "",
        author: "",
        press: "",
        date: "",
        cover: "",
        abs: "",
        cid: "",
      },
    };
  },
  components: {
    ImgUpload,
  },
  created() {
    this.getBookList();
  },
  methods: {
    // 获取一页图书
    async getBookList() {
      const { data: res } = await this.$http.get("admin/book", {
        params: this.queryInfo,
      });
      if (res && res.code !== 200) this.$message.error("获取图书失败");
      const loading = this.$loading({
        target: "#bookTable",
        lock: true,
      });
      this.bookList = res.data.bookList;
      this.count = res.data.count;
      loading.close();
    },

    // 显示修改图书信息的对话框
    showEditDialog(item) {
      this.addAndEditDialogVisible = true;
      this.dialogTitle = "修改《" + item.title + "》的信息";
      this.addAndEditForm = {
        id: item.id,
        cover: item.cover,
        title: item.title,
        author: item.author,
        date: item.date,
        press: item.press,
        abs: item.abs,
        cid: item.cid + "",
      };

      // this.$refs.addFormRef.validate(async (valid) => {
      //   // if (!valid) return this.$message.error("填写参数有误请重新填写");
      //   // const { data: res } = await this.$http.put("admin/book/"+queryInfo.pageNum, this.addAndEditForm);
      //   // console.log(data)
      //   // if (res && res.code !== 200) return this.$message.error("获取图书失败");
      //   //   this.addAndEditDialogVisible = false;
      //   //   this.$message.success("更新用户信息成功");
      //   //   this.getBookList();
      // });
    },

    // 添加/修改图书
    addOrEdit() {
      console.log("要修改的图书的 id：" + this.addAndEditForm.id);
      // 表单验证是否通过
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("参数有误，请修正");
        if (this.addAndEditForm.id !== undefined) {
          // 发起修改图书的请求
          const { data: res } = await this.$http.put(
            "admin/book",
            this.addAndEditForm
          );
          if (res.code !== 200)
            return this.$message.error("服务器错误，添加图书失败");
          this.$message.success("修改图书成功");
        } else {
          // 发起添加图书的请求
          const { data: res } = await this.$http.post(
            "admin/book",
            this.addAndEditForm
          );
          if (res.code !== 200)
            return this.$message.error("服务器错误，添加图书失败");
          this.$message.success("添加图书成功");
        }
        this.addAndEditDialogVisible = false;
        this.getBookList();
      });
    },

    // 删除图书
    async deleteBook(id) {
      const reslut = await this.$confirm(
        "此操作将永久删除该书籍, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (reslut !== "confirm") return this.$message.info("取消删除");
      const { data: res } = await this.$http.delete("admin/book", { id: id });
      if (res.code !== 200) return this.$message.error("删除失败");
      this.getBookList();
    },

    // 监听页码变化
    handleCurrentChange(currentPage) {
      this.queryInfo.pageNum = currentPage;
      this.getBookList();
    },

    // 监听添加图书对话框的关闭
    addAndEditDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    uploadImg() {
      this.addAndEditForm.cover = this.$refs.imgUploadRef.url;
    },
  },
};
</script>

<style scoped>
</style>
